package com;

import com.fz.entity.Student;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test;

import java.util.List;

/**
 * Created by Z-C-Y on 2018-02-28.
 */
public class Demo {
    @Test
    public void aa(){
        /*向数据库中添加数据*/
        Configuration cfg = new Configuration();
        cfg.configure();
        /*创建工厂*/
       SessionFactory sf = cfg.buildSessionFactory();
      Session s = sf.openSession();
      /*session.beginTransaction()在获得一个Transaction后调用其begin()方法*/
      Transaction tx = s.beginTransaction();
      Student  stu = new Student();
      stu.setName("张朝阳");
      stu.setAge(99);
      s.save(stu);/*save就是写入对对象*/
      tx.commit();/*提交事务*/
      s.close();/*关闭*/

    }

    @Test
     public void bb(){
        /*查询数据库中的所有的数据*/
        Configuration cfg = new Configuration();
        cfg.configure();
       SessionFactory sf =  cfg.buildSessionFactory();
       Session s = sf.openSession();
        List<Student> list = s.createQuery("from com.fz.entity.Student").list();
        for(Student ss:list){
            System.out.println(ss);
        }
        s.close();

     }

     @Test
     public void cc(){
        /*使用Hibernate删除数据据中的数据*/
        Configuration cfg = new Configuration().configure("hibernate.cfg.xml");
        SessionFactory sf = cfg.buildSessionFactory();
        Session s = sf.openSession();
         /*开启事务*/
         Transaction tx =  s.beginTransaction();
        Student stu = new Student();
        stu.setId(3);
        s.delete(stu);
        tx.commit();/*提交事务*/
        s.close();
        sf.close();
     }

    @Test
    public void dd(){
        /*使用Hibernate删除数据据中的数据*/
        Configuration cfg = new Configuration().configure("hibernate.cfg.xml");
        SessionFactory sf = cfg.buildSessionFactory();
        Session s = sf.openSession();
        /*开启事务*/
        Transaction tx =  s.beginTransaction();
        /*使用这种方式删除数据库中的数据，是先查，在进行删除*/
       s.delete(s.get(Student.class,12));
        tx.commit();/*提交事务*/
        s.close();
        sf.close();
    }

    @Test
    public void ee(){
        /*使用hibernate对数据库进行更改*/
        Configuration cfg = new Configuration().configure("hibernate.cfg.xml");
       SessionFactory sf =  cfg.buildSessionFactory();
       Session s = sf.openSession();
        Transaction tx = s.beginTransaction();
        Student stu = s.get(Student.class,22);
        stu.setAge(88);
        s.saveOrUpdate(stu);
        tx.commit();
        s.close();
        sf.close();

    }



}
